/*
 * @Description: 节流
 * @Version: 1.0.0
 * @Author: gyh
 * @Date: 2021-08-18 10:17:53
 * @LastEditors: gyh
 * @LastEditTime: 2021-08-18 11:40:45
 */
const TIMER = 200
window.addEventListener('scroll', throttle(handler))

let totop = document.getElementById('totop')
function handler() {
  let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  console.log(scrollTop)
  totop.style.display = scrollTop > 400 ? 'block' : 'none'
}

totop.onclick = function () {
  let scrollToptimer = setInterval(function () {
    let top = document.body.scrollTop || document.documentElement.scrollTop
    let speed = top / 4
    if (document.body.scrollTop != 0) {
      document.body.scrollTop -= speed
    } else {
      document.documentElement.scrollTop -= speed
    }
    if (top == 0) {
      clearInterval(scrollToptimer)
    }
  }, 30)
}

function throttle(fn, delay = TIMER) {
  let timer = null
  return function () {
    if (timer) return
    timer = setTimeout(() => {
      fn.call(this, arguments)
      timer = null
    }, delay)
  }
}
